package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public void hotCommentExecutor(ApComment apComment) {
        if (apComment.getLikes()>5&&apComment.getFlag().intValue()==0) {

            // 查询目前的热点评论
            Query query = Query.query(Criteria.where("entryId").is(apComment.getEntryId())
                    .and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC, "likes"));
            List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
            if (commentList == null || commentList.size() < 5) {
                // 直接把当前评论设置为设点评论
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
            } else {
                // 找到最小的那个判断
                ApComment lastHotApcomment = commentList.get(commentList.size() - 1);
                if (lastHotApcomment.getLikes() < apComment.getLikes()) {
                    // 只能说，吾可取而代之
                    apComment.setFlag((short) 1);
                    mongoTemplate.save(apComment);
                    lastHotApcomment.setFlag((short) 0);
                    mongoTemplate.save(lastHotApcomment);
                }
            }

        }
    }
}
